package application.smartcard;

import java.util.List;
import javax.smartcardio.*;

/**
 *
 * @author M. Cardinaux <matthieu.cardinaux at gmail.com>
 */
public class SmartCardManager {

    CardTerminal terminal;

    public SmartCardManager(int terminalNumber) throws CardException, InvalidTerminalNumberException, NoTerminalAvailableException {

        List<CardTerminal> listOfTerminals = getAvailableTerminals();
        if(listOfTerminals.isEmpty()) throw new NoTerminalAvailableException();
        if(terminalNumber+1>listOfTerminals.size()) throw new InvalidTerminalNumberException();
        terminal = listOfTerminals.get(terminalNumber);
        System.out.println("SELECTED TERMINAL");
        System.out.println("\t"+terminal);
        
    }

    public SmartCardManager() throws CardException, NoTerminalAvailableException, InvalidTerminalNumberException {
            this(0);
    }


    private List<CardTerminal> getAvailableTerminals() throws CardException {
        TerminalFactory tf = TerminalFactory.getDefault();
        CardTerminals terminals = tf.terminals();
        List<CardTerminal> listOfTerminals = terminals.list();
        System.out.println("AVAILABLE TERMINALS");
        for(CardTerminal ct : listOfTerminals){
            System.out.println("\t"+ct);
        }
        return listOfTerminals;
    }

    public void waitForCard() throws CardException {
        terminal.waitForCardPresent(0);
    }

    public SmartCard getSmartCard() throws CardException {
        return new SmartCard(terminal.connect("T=0"));
    }

    public void waitForCardWithdrawal() throws CardException {
        terminal.waitForCardAbsent(0);
    }
    
    
}